# -*- coding: utf-8 -*-

import os,re,shutil,logging
from .. import config as C
from .. import utils
from ..utils import py
from ..utils import fs
from ..build.caches.file_cache import FileCache

class AssetPublisher:
	'''
		资源发布器
	'''
	def __init__(self):
		self._config = utils.getConfig()
		self._publishForce = py.getDictPath(self._config, 'publish.force', False)
		self._publishTarget = py.getDictPath(self._config, 'publish.target', [])

	def collectFiles(self, originPackPath):
		'''
			收集文件
		'''
		includeFile = os.path.join(originPackPath, 'assets.include')
		if os.path.exists(includeFile):
			with open(includeFile, 'r', encoding='utf-8') as f:
				content = f.read()
				content = re.sub(r'[\r\n]+','\n', content)
				content = re.sub(r'[ ]','', content)
			includes = content.split('\n')
		else:
			includes = [ r'**/*' ]
		originAssetPath = os.path.join(originPackPath, 'assets')
		assetFiles = fs.globFiles(includes, originAssetPath)
		assetFiles = [ os.path.normpath(f) for f in assetFiles if os.path.isfile(f)]
		return assetFiles

	def checkUpdate(self):
		'''
			检测更新
		'''
		updates = set()
		for pack in os.listdir(C.BUILD_CACHES_PATH):
			fileCache = FileCache(os.path.join(C.BUILD_CACHES_PATH, pack, 'publish-assets-cache.json'))
			fileCache.load()
			assetFiles = self.collectFiles(os.path.normpath(utils.fullConfigPath(self._config['path']['origins'], pack)))
			if fileCache.checkFileChange(assetFiles):
				updates.add(pack)
		return updates
		
	def publishClient(self, packPath):
		'''
			发布包
		'''
		clientPath = os.path.normpath(utils.fullConfigPath(self._config['path']['client']))
		if os.path.exists(clientPath):
			pack = os.path.basename(packPath)
			clientPackPath = utils.getClientPackPath(os.path.join(clientPath,'assets'), pack)
			if clientPackPath != None:
				originPath = os.path.normpath(utils.fullConfigPath(self._config['path']['origins'], pack))
				assetFiles = self.collectFiles(originPath)

				clientPackRootPath = os.path.join(clientPackPath, 'lcc-assets')
				'''
				clientAssetPath = os.path.join(clientPackRootPath, 'assets')
				clientFiles = fs.globFiles([ r'**/*.*' ], clientAssetPath)
				clientFiles = [ os.path.normpath(f) for f in clientFiles if not f.endswith('.meta') and os.path.isfile(f)]
				for f in clientFiles:
					if f.replace(clientPackRootPath, originPath) not in assetFiles:
						os.remove(f)
						logging.info('remove unused asset `%s`' % f)
				'''

				# 复制新的资源文件
				for f in assetFiles:
					clientFile = f.replace(originPath, clientPackRootPath)
					if not os.path.exists(clientFile) or fs.getFileMD5(f) != fs.getFileMD5(clientFile):
						fileDir = os.path.dirname(clientFile)
						if not os.path.isdir(fileDir):
							os.makedirs(fileDir)
						shutil.copyfile(f, clientFile)
						logging.info('copy asset from `%s` to `%s`' % (f, clientFile))

			else:
				logging.warn('not found client pack `%s`' % pack)
				
		return True

	def publish(self):
		'''
			发布资源文件
		'''
		updates = self.checkUpdate()
		for f in os.listdir(C.BUILD_CACHES_PATH):
			packPath = os.path.join(C.BUILD_CACHES_PATH, f)
			if os.path.isdir(packPath):
				for target in self._publishTarget:
					if target == 'client' and (self._publishForce or (f in updates)):
						if not self.publishClient(packPath):
							return False
						fileCache = FileCache(os.path.join(packPath, 'publish-assets-cache.json'))
						fileCache.load()
						originPath = os.path.normpath(utils.fullConfigPath(self._config['path']['origins'], f))
						fileCache.updateFiles(self.collectFiles(originPath))
						fileCache.save()
		return True

def publish():
	return AssetPublisher().publish()
